require('dotenv').config({ path: __dirname + '/.env' })
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const fs = require('fs');
const path = require('path');
const routesDir = path.join(__dirname, 'routes')
const cors = require('koa2-cors');
const authenticateToken = require('./middleware/authMiddleware'); //  引入token验证中间件
const {  connectDB } = require('./public/javascripts/utils');
// 连接数据库
connectDB();
//  配置动态路由
fs.readdir(routesDir, (err, files) => { //  这里是为了读取routes文件夹下的所有文件
  const routers = []
  if (err) {
      console.error('Error reading directory:', err)
      return
  }
  files.forEach(router => {
    router = require(`./routes/${router}`)
    routers.push(router)
  })
  routers.forEach(router => app.use(router.routes(), router.allowedMethods()))
})



// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text'],
  formLimit: '50mb', //  默认56kb
  jsonLimit: '50mb', //  默认1mb
  textLimit: '50mb', //  默认1mb
}))
app.use(json())
app.use(logger())
// 允许跨域并传递 Authorization 头
app.use(cors({
  origin: '*',
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  // ctx.set("Access-Control-Allow-Origin", "*") //  允许跨域
  // ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  // ctx.set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})


// JWT 验证中间件
app.use(authenticateToken);
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
